<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-model="listQuery.type" placeholder="类型" class="filter-item">
        <el-option v-for="item in typeData" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-input v-model="listQuery.name$lk" placeholder="备注" class="filter-item" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter"
        >
        查询
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate"
        >
        添加
      </el-button>
      <el-button class="filter-item" type="danger" icon="el-icon-delete" @click="handlePlDelete"
        >
        批量删除
      </el-button>
    </div>
    <el-table v-loading="listLoading" :data="list" border fit highlight-current-row row-key="id"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}" style="width: 100%;"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40" />
      <el-table-column label="序号" type="index" align="center" width="60px" />
      <el-table-column label="商品名称" prop="name" align="center" />
      <el-table-column label="数量" prop="num" align="center" />
      <el-table-column label="仓位" prop="storeName" align="center" />
      <el-table-column label="类型" prop="typeText" align="center" />
      <el-table-column label="备注" prop="remark" align="center" />
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize"
      @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="60px"
        style="margin: 0 50px;">
        <el-form-item label="类型" prop="type">
          <el-select v-model="temp.type">
            <el-option v-for="item in typeData" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" />
        </el-form-item>
      </el-form>
      <el-card class="box-card" shadow="hover" style="margin:0 50px">
        <div slot="header" class="clearfix">
          <span>选择商品</span>
        </div>
        <Product ref="product" @productSelectionChange="productSelectionChange" />
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="saveData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { storePageByQo, storeRecordPageByQo, storeRecordRemoveByIds, storeRecordSave } from '@/api/store'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import Product from './product'
import qs from 'qs'

export default {
  name: 'StoreList',
  directives: { waves },
  components: { Pagination, Product },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        type: '',
        name$lk: '',
        storeId: ''
      },
      typeData: [
        { value: 1, label: '入库' },
        { value: 2, label: '出库' }
      ],
      temp: {
        id: 0,
        type: 2,
        json: '',
        remark: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑出入库',
        create: '添加出入库'
      },
      rules: {
        type: [{ required: true, message: '请选择', trigger: 'change' }],
      },
      multipleSelection: [],
      productSelection: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      storeRecordPageByQo(this.listQuery).then(response => {
        this.list = response.list || []
        this.total = response.totalCount
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: 0,
        type: 2,
        json: '',
        remark: ''
      }
    },
    handleCreate(row) {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.$refs['product'].resetNum()
      })
    },
    saveData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          delete this.temp.createTime
          if (!this.validateProduct()) {
            return
          }
          storeRecordSave(qs.stringify(this.temp)).then(() => {
            this.getList()
            this.dialogFormVisible = false
            // this.$notify({
            //   title: '成功',
            //   message: '保存成功',
            //   type: 'success',
            //   duration: 2000
            // })

            this.$message({
              message: '保存成功',
              type: 'success'
            });
          })
        }
      })
    },
    //商品选择
    productSelectionChange(val) {
      this.temp.json = val ? JSON.stringify(val) : ''
    },
    validateProduct() {
      let isOk = true
      if (this.temp.json) {
        let json = JSON.parse(this.temp.json)
        let item = json.find(item => {
          return item.num < 0 || (!item.num && item.num !== 0)
        });
        if (item) {
          isOk = false
          this.$message.error('选择的商品中数量未填写或数量填写错误')
        }
      } else {
        isOk = false
        this.$message.error('请至少选择一件商品进行操作')
      }
      return isOk
    },
    // 批量删除
    handleSelectionChange(val) {
      this.multipleSelection = val.map((ele) => {
        return ele.id
      })
    },
    handlePlDelete() {
      if (!this.multipleSelection || this.multipleSelection.length < 1) {
        this.$message.error('请至少选择一条数据')
        return
      }
      const params = {
        ids: this.multipleSelection.join(',')
      }
      this.$confirm('是否继续删除？').then(() => {
        storeRecordRemoveByIds(params).then(() => {
          // this.$notify({
          //   title: '成功',
          //   message: '批量删除成功！',
          //   type: 'success',
          //   duration: 2000
          // })

          this.$message({
            message: '批量删除成功！',
            type: 'success'
          });
          this.getList()
        })
      })
    }
  }
}
</script>
